<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 用户注册
 *
 * @author      Eden
 * @datetime    2016/11/30 22:22
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Regist_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        // 检查请求
        $this->_checkRequest($params);
        // 检查是否注册
        $this->_checkIfRegist($params['phone']);

        $send['state'] = false;
        do {

            $nowTime = dateTime();
            $pass = encryptPassword($params['password']);
            $nickName = !empty($params['nickName']) ? $params['nickName'] : substr_replace($params['phone'], '***', 3, 5);
            $userData = array(
                'phone' => $params['phone'],
                'nickName' => $nickName,
                'password' => value($pass, 'password'),
                'salt' => value($pass, 'salt'),
                'lastIp' => remoteAddr(),
                'lastTime' => $nowTime,
                'created' => $nowTime,
                'source' => $params['type'],
                'status' => 1
            );

            try{

                $userDb = clone($this->db);
                $userDb->trans_start();
                $userDb->insert('user', $userData);

                // $profileDb = clone($this->db);
                $userId = $userDb->insert_id();
                if (empty($userId)) {
                    $send['error'] = '注册失败';
                    break;
                }

                $profileData = array(
                    'userId' => $userId,
                    'avatar' => !empty($params['avatar']) ? $params['avatar'] : '',
                    'trueName' => ''
                );
                $userDb->insert('user_profile', $profileData);
                $userDb->trans_complete();

                if ($userDb->trans_status() === FALSE) {
                    $send['error'] = '注册失败';
                    break;
                } else {
                    $send['state'] = true;
                    $send['data'] = array(
                        'userId' => intval($userId),
                        'nickName' => $nickName,
                        'trueName' => '',
                        'phone' => value($params, 'phone'),
                        'avatar' => thumb($profileData['avatar'], 100, 100),
                        'lastTime' => dateTime(),
                        'lastIp' => remoteAddr(),
                        'status' => 1
                    );

                    $this->_afterLogin($userId, $params);
                    @statIncr('appUsers');
                }
            } catch(Exception $e) {
                $send['error'] = '注册失败';
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 修改登录状态
     * @param $userId
     * @param $params
     */
    private function _afterLogin($userId, $params)
    {
        $this->db->insert('user_mobile_login', array(
            'userId' => $userId,
            'deviceId' => $params['deviceId'],
            'type' => $params['type'],
            'loginTime' => dateTime()
        ));
    }

    /**
     * 检查请求参数
     * @param $params
     * @return bool
     */
    private function _checkRequest($params)
    {
        $send['state'] = false;
        do {
            // 检查 请求
            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            if (empty($params['deviceId'])) {
                $send['error'] = '设备号不能为空';
                break;
            }

            if (empty($params['nickName'])) {
                $send['error'] = '昵称不能为空';
                break;
            }

            // 检查字段
            if (empty($params['phone']) || !preg_match('/^1[34578]\d{9}$/', $params['phone'])) {
                $send['error'] = '手机号格式错误';
                break;
            }

            if (empty($params['password'])
                || strlen($params['password']) < 6 || strlen($params['password']) > 18) {
                $send['error'] = '密码错误';
                break;
            }

            return true;

        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查是否已经注册
     * @param $phone
     * @return bool
     */
    private function _checkIfRegist($phone)
    {
        $query = $this->db->get_where('user', array('phone' => $phone));
        $result = $query->row_array();
        if ($result) {
            $this->output->send(array(
                'state' => false,
                'error' => '该手机号已注册'
            ));
            exit;
        }
        return true;
    }
}
